package com.ny.controller;

import com.ny.entity.Result;
import com.ny.entity.User;
import com.ny.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@CrossOrigin(origins = "*", maxAge = 3600)
public class UserController {

    @Autowired
    private UserService userService;

    // 登录请求DTO
    public static class LoginRequest {
        private String username;
        private String password;

        public LoginRequest() {}

        public LoginRequest(String username, String password) {
            this.username = username;
            this.password = password;
        }

        public String getUsername() { return username; }
        public void setUsername(String username) { this.username = username; }
        public String getPassword() { return password; }
        public void setPassword(String password) { this.password = password; }
    }

    // 修复的登录接口 - 同时支持表单和JSON
    @PostMapping("/login")
    public Result login(
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String password,
            @RequestBody(required = false) LoginRequest loginRequest) {
        try {
            System.out.println("=== 收到登录请求 ===");

            // 处理参数来源
            String finalUsername = null;
            String finalPassword = null;

            if (loginRequest != null) {
                finalUsername = loginRequest.getUsername();
                finalPassword = loginRequest.getPassword();
                System.out.println("从JSON体获取参数 - 用户名: " + finalUsername);
            } else {
                finalUsername = username;
                finalPassword = password;
                System.out.println("从表单参数获取 - 用户名: " + finalUsername);
            }

            // 参数验证
            if (finalUsername == null || finalUsername.trim().isEmpty()) {
                System.out.println("❌ 用户名为空");
                return Result.error("用户名不能为空");
            }
            if (finalPassword == null || finalPassword.trim().isEmpty()) {
                System.out.println("❌ 密码为空");
                return Result.error("密码不能为空");
            }

            finalUsername = finalUsername.trim();
            finalPassword = finalPassword.trim();

            System.out.println("✅ 参数验证通过 - 用户名: " + finalUsername + ", 密码长度: " + finalPassword.length());

            // 调用服务层进行用户验证
            User user = userService.findUser(finalUsername, finalPassword);
            if (user != null) {
                System.out.println("✅ 登录成功 - 用户ID: " + user.getUser_id() + ", 用户名: " + user.getUsername());

                Map<String, Object> data = new HashMap<>();
                data.put("user", user);
                data.put("token", "token_" + System.currentTimeMillis());
                return Result.success("登录成功", data);
            } else {
                System.out.println("❌ 用户名或密码错误 - 用户名: " + finalUsername);
                return Result.error("用户名或密码错误");
            }
        } catch (Exception e) {
            System.err.println("❌ 登录异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("登录失败: " + e.getMessage());
        }
    }

    // 删除用户接口 - 完整修复版本
    @DeleteMapping("/delete/{userId}")
    public Result deleteUser(@PathVariable("userId") Integer userId, HttpServletRequest request) {
        try {
            System.out.println("=== 收到删除用户请求 ===");
            System.out.println("请求方法: " + request.getMethod());
            System.out.println("请求URL: " + request.getRequestURL());
            System.out.println("用户ID: " + userId);
            System.out.println("用户ID类型: " + (userId != null ? userId.getClass().getSimpleName() : "null"));

            // 检查用户是否存在
            User userToDelete = userService.getUserById(userId);
            if (userToDelete == null) {
                System.out.println("❌ 用户不存在，ID: " + userId);
                return Result.error("用户不存在");
            }

            System.out.println("✅ 找到要删除的用户: " + userToDelete.getUsername());

            int result = userService.deleteUser(userId);
            System.out.println("✅ 数据库删除操作结果: " + result);

            if (result > 0) {
                System.out.println("✅ 用户删除成功");
                return Result.success("用户删除成功");
            } else {
                System.out.println("❌ 删除用户失败，影响行数: " + result);
                return Result.error("删除用户失败");
            }
        } catch (Exception e) {
            System.err.println("❌ 删除用户异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("删除用户失败: " + e.getMessage());
        }
    }

    // 获取所有用户信息
    @GetMapping("/getAllUsers")
    public Result getAllUsers() {
        try {
            System.out.println("=== 获取所有用户列表 ===");
            List<User> users = userService.getAllUsers();
            System.out.println("✅ 成功获取 " + users.size() + " 个用户");
            return Result.success("获取用户列表成功", users);
        } catch (Exception e) {
            System.err.println("❌ 获取用户列表异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("获取用户列表失败: " + e.getMessage());
        }
    }

    // 注册接口
    @PostMapping("/register")
    public Result register(
            @RequestParam String username,
            @RequestParam String password,
            @RequestParam(required = false) String nickname,
            @RequestParam(required = false) String email,
            @RequestParam(required = false) String phone) {
        try {
            System.out.println("=== 注册新用户 ===");
            System.out.println("用户名: " + username + ", 昵称: " + nickname + ", 邮箱: " + email + ", 电话: " + phone);

            // 参数验证
            if (username == null || username.trim().isEmpty()) {
                return Result.error("用户名不能为空");
            }
            if (password == null || password.trim().isEmpty()) {
                return Result.error("密码不能为空");
            }

            User user = new User();
            user.setUsername(username.trim());
            user.setPassword(password.trim());
            user.setNickname(nickname != null ? nickname.trim() : "");
            user.setEmail(email != null ? email.trim() : "");
            user.setPhone(phone != null ? phone.trim() : "");
            user.setIs_active(1);

            int result = userService.addUser(user);
            if (result > 0) {
                System.out.println("✅ 用户注册成功 - 用户名: " + username);
                return Result.success("注册成功");
            } else {
                System.out.println("❌ 用户注册失败 - 用户名: " + username);
                return Result.error("注册失败");
            }
        } catch (Exception e) {
            System.err.println("❌ 注册异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("注册失败: " + e.getMessage());
        }
    }

    // 修改密码接口
    @PostMapping("/changePassword")
    public Result changePassword(
            @RequestParam Integer user_id,
            @RequestParam String new_password) {
        try {
            System.out.println("=== 修改密码 ===");
            System.out.println("用户ID: " + user_id + ", 新密码长度: " + (new_password != null ? new_password.length() : 0));

            User user = userService.getUserById(user_id);
            if (user == null) {
                System.out.println("❌ 用户不存在 - ID: " + user_id);
                return Result.error("用户不存在");
            }

            int result = userService.updatePassword(new_password, user.getEmail());
            if (result > 0) {
                System.out.println("✅ 密码修改成功 - 用户ID: " + user_id);
                return Result.success("密码修改成功");
            } else {
                System.out.println("❌ 密码修改失败 - 用户ID: " + user_id);
                return Result.error("密码修改失败");
            }
        } catch (Exception e) {
            System.err.println("❌ 修改密码异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("修改密码失败: " + e.getMessage());
        }
    }

    // 根据邮箱查找用户
    @GetMapping("/findUserByEmail")
    public Result findUserByEmail(@RequestParam String email) {
        try {
            System.out.println("=== 根据邮箱查找用户 ===");
            System.out.println("邮箱: " + email);

            User user = userService.findUserByEmail(email);
            if (user != null) {
                System.out.println("✅ 找到用户 - 用户名: " + user.getUsername());
                return Result.success(user);
            } else {
                System.out.println("❌ 该邮箱不存在: " + email);
                return Result.error("该邮箱不存在");
            }
        } catch (Exception e) {
            System.err.println("❌ 查询用户异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("查询失败: " + e.getMessage());
        }
    }

    // 发送邮件
    @GetMapping("/sendEmail")
    public Result sendEmail(@RequestParam String toEmail) {
        try {
            System.out.println("=== 发送邮件 ===");
            System.out.println("目标邮箱: " + toEmail);

            if (toEmail != null && userService.findUserByEmail(toEmail) != null) {
                userService.sendToEmail(toEmail);
                System.out.println("✅ 邮件发送成功 - 邮箱: " + toEmail);
                return Result.success("发送成功");
            }
            System.out.println("❌ 发送失败，该邮箱不存在: " + toEmail);
            return Result.error("发送失败,该邮箱不存在");
        } catch (Exception e) {
            System.err.println("❌ 发送邮件异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("发送失败: " + e.getMessage());
        }
    }

    // 更新密码（带验证码）
    @PutMapping("/updatePassword")
    public Result updatePassword(
            @RequestParam String code,
            @RequestParam String password,
            @RequestParam String email) {
        try {
            System.out.println("=== 更新密码（带验证码）===");
            System.out.println("邮箱: " + email + ", 验证码: " + code + ", 密码长度: " + password.length());

            if (userService.checkCode(email, code)) {
                int i = userService.updatePassword(password, email);
                if (i > 0) {
                    System.out.println("✅ 密码修改成功 - 邮箱: " + email);
                    return Result.success("修改密码成功");
                }
            }
            System.out.println("❌ 密码修改失败 - 邮箱: " + email);
            return Result.error("修改密码失败");
        } catch (Exception e) {
            System.err.println("❌ 更新密码异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("修改密码失败: " + e.getMessage());
        }
    }

    // 健康检查接口
    @GetMapping("/health")
    public Result healthCheck() {
        return Result.success("用户服务正常运行");
    }

    // 获取当前用户信息
    @GetMapping("/profile/{userId}")
    public Result getUserProfile(@PathVariable Integer userId) {
        try {
            System.out.println("=== 获取用户信息 ===");
            System.out.println("用户ID: " + userId);

            User user = userService.getUserById(userId);
            if (user != null) {
                System.out.println("✅ 获取用户信息成功 - 用户名: " + user.getUsername());
                return Result.success(user);
            } else {
                System.out.println("❌ 用户不存在 - ID: " + userId);
                return Result.error("用户不存在");
            }
        } catch (Exception e) {
            System.err.println("❌ 获取用户信息异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("获取用户信息失败: " + e.getMessage());
        }
    }
}